package com.biu.websocket;

import java.io.UnsupportedEncodingException;

import javax.inject.Inject;
import javax.inject.Named;

import org.atmosphere.config.service.Disconnect;
import org.atmosphere.config.service.Heartbeat;
import org.atmosphere.config.service.ManagedService;
import org.atmosphere.config.service.Message;
import org.atmosphere.config.service.Ready;
import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.AtmosphereResourceEvent;
import org.atmosphere.cpr.Broadcaster;


@ManagedService(path = "/websocket/chat", atmosphereConfig = {
        "org.atmosphere.cpr.CometSupport.maxInactiveActivity=120000"}, broadcastFilters = {MessageFilter.class})
public class WebSocket {

    /**
     *
     */
    private static final long serialVersionUID = 1L;


    @Inject
    private AtmosphereResource r;

    @Inject
    @Named("/websocket/chat")
    public static Broadcaster broadcaster;

    /**
     * 打开连接时触发
     *
     * @throws UnsupportedEncodingException
     */
    @Ready
    public void onReady() throws UnsupportedEncodingException {
        System.out.println("user connected : " + r.getRequest().getHeader("username"));
    }

    @Disconnect
    public void onDisconnect(AtmosphereResourceEvent event) throws UnsupportedEncodingException {
        // 获取用户信息
        String username = r.getRequest().getHeader("username");
        if (event.isCancelled()) {// 非正常关闭时触发，报错了
            System.out.println("user accidental disconnected : " + username);
        } else if (event.isClosedByClient()) {// 关闭连接时触发
            System.out.println("user accidental disconnected : " + username);
            System.out.println("user disconnected : " + username);
        }
    }

    /**
     * 接收到消息
     */
    @Message(decoders = {MessageReceiveDecoder.class})
    public void onMessage(com.biu.websocket.Message data) {
        System.out.println("消息内容： " + data);
    }

    @Heartbeat
    public void onHeartbeat(AtmosphereResourceEvent event) {
        System.out.println("Heartbeat send by {" + event.getResource().uuid() + "}");
    }
}

